"""
文件上传器例子的UI层
"""
import asyncio
import typing

from elio import core
base_url = core.file_upload_serve('', '/upload')


class FileUploaderLayer(core.AutoRecycleLayer[core.Activity]):
    clMain: core.ColumnLayout = None
    mpAudio: core.MediaPlayer = None

    async def on_create(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_create(*args, *kwargs)

    async def on_hide(self):
        await super().on_hide()
        if self.clMain:
            await self.clMain.destroy()
        if self.mpAudio:
            await self.mpAudio.destroy()

    async def on_show(self):
        await super().on_show()
        activity = self.parent
        self.clMain = await core.ColumnLayout.create(activity)
        wfu_audio = await self.clMain.add(core.WidgetFileUploader, .1, widget_args=('请选择音频',))
        await wfu_audio.set_mime_type('audio/*')
        print(await wfu_audio.get_mime_type())
        wb_preview = await self.clMain.add(core.WidgetButton, .1, widget_args=('预览',))
        self.mpAudio = await core.MediaPlayer.create(activity)
        await self.mpAudio.load_from_widget_file_uploader(wfu_audio)

        async def cb_preview():
            """
            预览按钮点击事件。
            """
            await self.mpAudio.play()

        await wb_preview.set_on_click_listener(cb_preview)

        wb_upload = await self.clMain.add(core.WidgetButton, .1, widget_args=('上传',))

        async def cb_upload():
            """
            上传按钮点击事件。
            """
            wpb_upload = await self.clMain.add(core.WidgetProgressBar, .1)
            await wpb_upload.set_range(0, 100)
            print(await wpb_upload.get_range())

            async def cb_progress(progress: float):
                """
                上传进度事件。
                :param progress: 进度值。
                """
                await wpb_upload.set_value(int(progress))
                print('已上传%.2f%%' % progress, await wpb_upload.get_value())

            print('开始上传', await wfu_audio.get_filename())
            await wfu_audio.upload(base_url, cb_progress)
            print('上传完毕。')
            await asyncio.sleep(1)
            await self.clMain.remove(wpb_upload)

        await wb_upload.set_on_click_listener(cb_upload)

    async def on_pause(self):
        await super().on_pause()

    async def on_resume(self):
        await super().on_resume()

    async def on_destroy(self, *args: typing.Any, **kwargs: typing.Dict):
        await super().on_destroy(*args, **kwargs)
